﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;

namespace CPPEI.Net.UDP
{
    public class UDPClientReceiveThread
    {
        private Thread _thread;
        private bool _isRunning = false;
        private bool _isReceiving = false;

        private EventWaitHandle _eventHandle;

        byte[] _buffer;
        int _receiveLength;
        UDPClient _client;

        public UDPClientReceiveThread(UDPClient client)
        {
            _buffer = new byte[50*1024*1024];
            this._client = client;
            //_requestResolver = new RequestResolver();

            //_actionDispacher = new RPGHandle();
        }

        public void Start()
        {
            //Console.WriteLine("server start receive");
            if (this._thread != null)
            {
                this._isRunning = false;
                this._eventHandle.WaitOne();
            }

            this._eventHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
            this._thread = new Thread(Running);
            this._thread.Name = "recvThread" + Guid.NewGuid().ToString("N");
            this._isRunning = true;
            //Console.WriteLine("receive start");
            this._thread.Start();
        }

        public void Stop()
        {
            this._isRunning = false;
            this._eventHandle.WaitOne();
            //Console.WriteLine("server stop receive");
        }

        private void Running()
        {
            //Console.WriteLine("receive thread start");
            while (_isRunning)
            {
                _client.ReceiveAsync();
                Thread.Sleep(100);
            }

            this._eventHandle.Set();
            //Console.WriteLine("receive thread stop");
        }

        //private NetBufferPool _netBufferPool = new NetBufferPool();
    }
}
